package com.runtime.hongyunuser.controller;

import com.github.pagehelper.PageInfo;
import com.runtime.hongyunuser.bean.*;
import com.runtime.hongyunuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody Users users, HttpServletRequest req){
        Users result = userService.login(users);
        boolean flag = result != null;
        String msg = flag ? "登陆成功":"登陆失败";
        if (flag){
            req.getSession().setAttribute("loginAcc",result);
        }
        return new Result(flag? Code.GET_OK:Code.GET_ERR,flag,msg);
    }

    @GetMapping("getMenu")
    public Result getMenu(HttpServletRequest req){
        List<Categories> result = userService.getMenu();
        boolean flag =  result.size() > 0;
        String msg = flag ? "获取成功":"获取失败";
        int code = flag ? Code.GET_OK:Code.GET_ERR;
        return new Result(code, result, msg);
    }

    @GetMapping("/getLoginAcc")
    public Result getLoginAcc(HttpServletRequest req){
        Users loginAcc = (Users) req.getSession().getAttribute("loginAcc");
        int code = loginAcc != null ? Code.GET_OK:Code.GET_ERR;
        String msg = loginAcc != null ? "获取成功":"获取失败";
        return new Result(code, loginAcc, msg);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest req){
        req.getSession().removeAttribute("loginAcc");
        return new Result(Code.GET_OK, true, "退出成功");
    }


    //    我的订单
    @GetMapping("/getOrderList")
    public Result getOrderList(
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String productNumber, // 新增商品货号参数
            @RequestParam(required = false) String status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest request
    ) {

        Users loginUser = (Users) request.getSession().getAttribute("loginAcc");;
        Long userId=loginUser.getUserId();

        // 调用Service
        PageInfo<OrderDTO> result = userService.getOrderList(
                userId,
                orderNumber,
                productNumber, // 传递商品货号参数
                status,
                startDate,
                endDate,
                pageNum,
                pageSize
        );

        // 构建返回结果
        boolean flag = result.getList() != null && !result.getList().isEmpty();
        String msg = flag ? "查询成功" : "未找到符合条件的订单";
        int code = flag ? Code.GET_OK : Code.GET_ERR;

        return new Result(code, result, msg);
    }

    // 获取用户地址列表
    @GetMapping("/getUserAddressList")
    public Result getUserAddressList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest request) {

        Users loginUser = (Users) request.getSession().getAttribute("loginAcc");;
        Long userId=loginUser.getUserId();

        PageInfo<Useraddresses> pageInfo = userService.selectUserAddresses(userId, pageNum, pageSize);

        boolean flag = pageInfo.getList() != null && !pageInfo.getList().isEmpty();
        String msg = flag ? "查询成功" : "未找到地址";
        int code = flag ? Code.GET_OK : Code.GET_ERR;

        return new Result(code, pageInfo, msg);
    }

    // 设置默认地址
    @PostMapping("/setDefaultAddress")
    public Result setDefaultAddress(@RequestBody Map<String, Long> params,
                                    HttpServletRequest request) {
        try {
            Users loginUser = (Users) request.getSession().getAttribute("loginAcc");;
            Long userId=loginUser.getUserId();

            Long addressId = params.get("addressId");

            if (addressId == null) {
                return new Result(Code.BUSINESS_ERR, null, "地址ID不能为空");
            }

            // 调用Service（事务由接口注解保证）
            int affected = userService.setDefaultAddress(addressId, userId);

            // 总是返回成功（因为异常已被处理）
            // 这里需要传入 pageNum 和 pageSize 来获取分页数据
            PageInfo<Useraddresses> pageInfo = userService.selectUserAddresses(userId, 1, 10); // 默认第1页，每页10条
            List<Useraddresses> addresses = pageInfo.getList(); // 获取当前页的数据

            return new Result(
                    Code.UPDATE_OK,
                    addresses, // 返回当前页的数据（而不是整个 PageInfo）
                    "默认地址设置成功"
            );

        } catch (RuntimeException e) {
            // 业务异常（会自动触发事务回滚）
            return new Result(Code.BUSINESS_ERR, null, e.getMessage());
        } catch (Exception e) {
            // 系统异常
            return new Result(Code.SYSTEM_ERR, null, "系统繁忙");
        }
    }

    // 获取区域列表
    @GetMapping("/getRegions")
    public Result getRegions(@RequestParam(required = false) Integer parentId) {
        try {
            // 如果parentId为空，则查询省级区域(parentId=0)
            List<Regions> regions = userService.getRegionsByParentId(parentId != null ? parentId : 0);
            return new Result(Code.GET_OK, regions, "查询成功");
        } catch (Exception e) {
            return new Result(Code.GET_ERR, null, "查询区域失败");
        }
    }

    // 添加收货地址
    @PostMapping("/addAddress")
    public Result addAddress(@RequestBody Useraddresses useraddresses) {
        try {
            userService.addUserAddress(useraddresses);
            return new Result(Code.SAVE_OK, null, "添加成功");
        } catch (Exception e) {
            return new Result(Code.SAVE_ERR, null, e.getMessage());
        }
    }

    // 更新收货地址
    @PutMapping("/updateAddress")
    public Result updateAddress(@RequestBody Useraddresses useraddresses) {
        try {
            userService.updateUserAddress(useraddresses);
            // 返回更新后的地址列表
            PageInfo<Useraddresses> pageInfo = userService.selectUserAddresses(1L, 1, 10);
            return new Result(Code.UPDATE_OK, pageInfo.getList(), "地址更新成功");
        } catch (Exception e) {
            return new Result(Code.UPDATE_ERR, null, e.getMessage());
        }
    }

    // 删除收货地址
    @DeleteMapping("/deleteAddress/{addressId}")
    public Result deleteAddress(@PathVariable Long addressId,
                                HttpServletRequest request) {
        try {
            Users loginUser = (Users) request.getSession().getAttribute("loginAcc");;
            Long userId=loginUser.getUserId();

            userService.deleteUserAddress(addressId, userId);
            // 返回删除后的地址列表
            PageInfo<Useraddresses> pageInfo = userService.selectUserAddresses(userId, 1, 10);
            return new Result(Code.DELETE_OK, pageInfo.getList(), "地址删除成功");
        } catch (Exception e) {
            return new Result(Code.DELETE_ERR, null, e.getMessage());
        }
    }

    // 订单详情接口
    @GetMapping("/getOrderDetail")
    public Result getOrderDetail(@RequestParam String orderNumber) {
        OrderDTO order = userService.getOrderDetail(orderNumber);
        return new Result(Code.GET_OK, order, "查询成功");
    }

    // 订单商品明细接口
    @GetMapping("/getOrderItems")
    public Result getOrderItems(@RequestParam String orderNumber) {
        List<OrderItemDTO> items = userService.getOrderItems(orderNumber);
        return new Result(Code.GET_OK, items, "查询成功");
    }
    // 订单收货地址接口
    @GetMapping("/getOrderShippingAddress")
    public Result getOrderShippingAddress(@RequestParam String orderNumber) {
        try {
            ShippingAddressDTO address = userService.getOrderShippingAddress(orderNumber);
            return new Result(Code.GET_OK, address, "查询成功");
        } catch (Exception e) {
            return new Result(Code.GET_ERR, null, e.getMessage());
        }
    }

    // 获取用户地址列表
    @GetMapping("/getUserAddress")
    public Result getUserAddress(HttpServletRequest request) {

        Users loginUser = (Users) request.getSession().getAttribute("loginAcc");;
        Long userId=loginUser.getUserId();

        List<Useraddresses> address = userService.selectUserAddress(userId);

        boolean flag = address != null && !address.isEmpty();
        String msg = flag ? "查询成功" : "未找到地址";
        int code = flag ? Code.GET_OK : Code.GET_ERR;

        return new Result(code, address, msg);
    }


    @PostMapping("/insertOrder")
    public Result insertOrder(@RequestBody Orders orders) {
        try {
            // 1. 生成订单编号
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String orderNumber = "ORD" + sdf.format(new Date());
            orders.setOrderNumber(orderNumber);

            // 2. 设置订单状态为"processing"
            orders.setStatus("processing");

            // 3. 计算总金额（如果前端没有计算）
            if (orders.getItems() != null) {
                BigDecimal totalAmount = orders.getItems().stream()
                        .map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                orders.setTotalAmount(totalAmount.doubleValue());
            }

            // 4. 插入订单和商品
            int result = userService.insertOrder(orders);

            if (result > 0) {
                return new Result(Code.SAVE_OK, orderNumber, "订单创建成功");
            } else {
                return new Result(Code.SAVE_ERR, null, "订单创建失败");
            }
        } catch (Exception e) {
            return new Result(Code.SAVE_ERR, null, "订单创建失败: " + e.getMessage());
        }
    }

    @GetMapping("/api/current-user-id")
    public ResponseEntity<Long> getCurrentUserId(HttpServletRequest request) {
        Users loginUser = (Users) request.getSession().getAttribute("loginAcc");

        if (loginUser == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // 401 未授权
        }

        return ResponseEntity.ok(loginUser.getUserId()); // 直接返回 userId
    }

}
